import { useState, useEffect, forwardRef, useImperativeHandle } from 'react';
import { cloneDeep } from 'lodash';
import { Card, Button, Checkbox, Toast, Dialog, InfiniteScroll, SpinLoading } from 'antd-mobile';
import { TextWidget, getMessage } from '@inbiz/react';
import { getEditor } from '@inbiz/utils';
import NoData from '../NoData/ListNoData';
import { toggleSelect, getFormData } from '../utils';
import { setTasks, getTasks } from './service';
import { getSummary } from '../../commonUtils';
import './index.less';

const ProcessReceive = forwardRef((props: any, ref) => {
  const { userInfo, rangeConfig, processGroup } = props;
  const [selectItem, setSelectItem] = useState<any[]>([]);
  const [receiveData, setReceiveData] = useState<any[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [requestDone, setRequestDone] = useState(false);
  const [hasMore, setHasMore] = useState<boolean>(true);
  const [page, setPage] = useState(1);
  const isEditor = getEditor();

  let pageCheck = null;

  const formatServer = (
    pageIndex: number,
    data: {
      total: number; rows: any[]
    } = { rows: [], total: 0 },
  ) => {
    setRequestDone(true);
    const state = data !== null;
    let row: any[] = [];
    let checkDataIsNull: boolean | number = false;
    let changeArr: any[] = [];
    let isAdd = false;

    const nowPage = pageIndex;
    if (state) {
      // 判断请求是否成功
      row = data.rows.map((item) => {
        return {
          ...item,
          summary:
            item.summary && item.summary.startsWith('<')
              ? getSummary(item.summary)
              : item.summary,
        };
      });
      checkDataIsNull = row.length && row.length < 1; // 判断是否有数据
      pageCheck = () => {
        // 处理数据
        if (checkDataIsNull) {
          setHasMore(false);
        } else {
          const more = pageIndex < Math.ceil(data.total / 20);
          changeArr = row;
          setHasMore(more);
          setPage(nowPage + 1);
        }
      };
      // 判断页面为1
      if (nowPage == 1) {
        pageCheck();
      } else {
        isAdd = true;
        pageCheck();
      }
      if (isAdd) {
        // 判断是不是有分页数据
        let _assignedData = receiveData;
        setReceiveData([..._assignedData, ...changeArr])
        setSelectItem([..._assignedData, ...changeArr])
      } else {
        setReceiveData(changeArr);
        setSelectItem(changeArr);
      }
    } else {
      setHasMore(false);
      if (pageIndex == 1) {
        setReceiveData([]);
        setSelectItem([]);
      }
    }
  };

  const getList = async (
    value: string,
    pageIndex: number,
    searchC?: any,
  ) => {
    if (!requestDone) {
      setLoading(true);
    }
    const drparams = getFormData(userInfo, pageIndex, value);
    let res = await getTasks({
      ...drparams,
      dptKey:
        rangeConfig == 'all' || processGroup?.selectedRows?.length == 0
          ? ''
          : processGroup?.groupGuid ?? '',
    });
    formatServer(pageIndex, res?.details);
    setLoading(false);
  };

  const changeBox = (checked: boolean, item: { taskId: string }) => {
    const newArr = cloneDeep(selectItem);
    const index = newArr.findIndex((ele: { taskId: string; }) => item.taskId == ele.taskId);
    newArr[index].checked = checked;
    setSelectItem(newArr);
  };

  const claim = () => {
    const ids = selectItem
      .filter((item: { checked: boolean; taskId: string }) => item.checked && item.taskId)
      .map((ele: { taskId: any; }) => ele.taskId);
    if (ids.length < 0) {
      return Toast.show({ content: getMessage('processCenter.selectTask') });
    }
    const taskIds = ids.join(',');
    const params = {
      taskIds: taskIds,
      claimantId: userInfo.ID,
    };
    Dialog.confirm({
      content: `${getMessage('processCenter.confirmClaim')}${ids.length}${getMessage(
        'processCenter.tasks',
      )}？`,
      onConfirm: () => {
        setLoading(true);
        setTasks(params).then(async (res) => {
          if (res.code == '200') {
            Toast.show({ content: res.message });
            await getList('', 1);
          } else {
            Toast.show({ icon: 'fail', content: res.message });
          }
          setLoading(false);
        }).catch((error) => { setLoading(false); });
      },
    });
  };

  useEffect(() => {
    getList('', 1);
  }, []);

  useImperativeHandle(ref, () => ({
    getList: async (text: string, condition?: any) => {
      getList(text, 1, condition);
    },
  }));

  return (
    <div className={'processReceive'}>
      {loading ? (
        <div className={'loading'}>
          <SpinLoading />
        </div>
      ) : receiveData.length > 0 ? (
        <>
          {receiveData.map((item: any) => {
            return (
              <Card
                className={'receiveContainer'}
                title={item.processName}
                extra={
                  <Checkbox
                    checked={selectItem.find((ele: { taskId: any; }) => item.taskId == ele.taskId)?.checked || false}
                    onChange={(checked) => changeBox(checked, item)}
                  />
                }
                key={item.taskId}
              >
                <p>
                  <TextWidget>processCenter.tasksId</TextWidget>: {item.taskId}
                </p>
                <div style={{ display: 'flex' }}>
                  <p style={{ marginRight: 40 }}>
                    <TextWidget>processCenter.instanceNumber</TextWidget>: {item.processInstanceId}
                  </p>
                  <p style={{ flex: 1 }}>
                    <TextWidget>processCenter.taskProcess</TextWidget>: {item.stepName}
                  </p>
                </div>
              </Card>
            );
          })}
          <footer className={'operationFooter'} style={{ width: isEditor ? '19.5%' : '100%' }}>
            <div>
              {selectItem.filter((item: { checked: boolean }) => item.checked).length !==
                selectItem.length && (
                  <Button
                    color="primary"
                    fill="none"
                    onClick={() => toggleSelect(true, receiveData, setSelectItem)}
                  >
                    <TextWidget>processCenter.selectAll</TextWidget>
                  </Button>
                )}
              {selectItem.filter((item: { checked: boolean }) => item.checked).length ==
                selectItem.length && (
                  <Button
                    color="primary"
                    fill="none"
                    onClick={() => toggleSelect(false, receiveData, setSelectItem)}
                  >
                    <TextWidget>processCenter.cancelSelectAll</TextWidget>
                  </Button>
                )}
              {Boolean(selectItem.filter((item: { checked: boolean }) => item.checked).length) && (
                <span className={'selectedNumber'}>
                  <TextWidget>processCenter.haveselected</TextWidget>
                  {selectItem.filter((item: { checked: boolean }) => item.checked).length}
                  <TextWidget>processCenter.item</TextWidget>
                </span>
              )}
            </div>
            <div>
              <Button
                color="primary"
                onClick={claim}
                disabled={selectItem.filter((item: { checked: any; }) => item.checked).length == 0}
              >
                <TextWidget>processCenter.claim</TextWidget>
              </Button>
            </div>
          </footer>
          <InfiniteScroll loadMore={() => getList('', page)} hasMore={hasMore} />
        </>
      ) : (
        <NoData />
      )}
    </div>
  );
});

export default ProcessReceive;
